package com.zzlzd.drp.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.lang.UUID;
import com.google.zxing.WriterException;
import com.qiniu.storage.model.DefaultPutRet;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.zzlzd.drp.config.BaseConfig;
import com.zzlzd.drp.config.ResponseInfo;
import com.zzlzd.drp.config.ResultGenerator;
import com.zzlzd.drp.config.WxMA.WxMaConfiguration;
import com.zzlzd.drp.config.RedisUtils;
import com.zzlzd.drp.domain.*;
import com.zzlzd.drp.util.*;
import me.chanjar.weixin.common.error.WxErrorException;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;



@RestController
@RequestMapping("/api")
public class ApiController {
    @Autowired
    RedisUtils redisUtils;
    @Autowired
    BaseConfig baseConfig;
    @Autowired
    UserRepository userRep;
    @Autowired
    private HttpServletRequest req;

    @Autowired
    SwiperRep swiperRep;
    @Autowired
    AddressRep addressRep;
    @Autowired
    RelationRep relationRep;
    @Autowired
    MoneyLogRep moneyLogRep;
    @Autowired
    GoodsRep goodsRep;

    @Autowired
    GoodsMenuRep goodsMenuRep;

    @Autowired
    OrdersRep ordersRep;
    @Autowired
    StudyCodeRep studyCodeRep;

    @Autowired
    OrderInfoRep orderInfoRep;


    @Autowired
    ArticleRep articleRep;
    @Autowired
    RankRep rankRep;
    @Autowired
    MenuRep menuRep;
    @Autowired
    DesignRep designRep;

    @Autowired
    ResultGenerator r;

    @PersistenceContext
    private EntityManager entityManager;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    private static String appId = "wx2f72c2fd30a9f48e";
    private static String secret = "380198d6f8fff0d0d42a3e08d233c75b";

    private static String[] adminOpenId ={"on-Vh5VKghMscXRCF_KnOru_VPXE"};



    @GetMapping("/test")
    public String test(){
        return "部署成功";
    }

    /***
     * 商城商品分类
     * @return
     */
    @GetMapping("/menu")
    public ResponseInfo menu(){
        JSONArray goodsMenu = new JSONArray();
        List<GoodsMenuDto> goodsMenuDtoList = goodsMenuRep.getMenu();
        for(GoodsMenuDto goodsMenuDto:goodsMenuDtoList){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name",goodsMenuDto.getMenuName());
            JSONArray jsonArray = new JSONArray();
            List<Map<String,Object>> goodsList = goodsRep.getGoodsMenuByMid(goodsMenuDto.getId());
            for(Map<String,Object> map:goodsList){
                JSONObject goods = new JSONObject();
                goods.put("name",map.get("goods_name"));
                goods.put("key",map.get("id"));
                goods.put("icon",map.get("goods_img"));
                goods.put("cat",Integer.parseInt(map.get("mid").toString()));
                jsonArray.add(goods);
            }
            jsonObject.put("foods",jsonArray);
            goodsMenu.add(jsonObject);
        }
        return r.sd(goodsMenu);
    }
    /***
     * 文章中心
     * @return
     */
    @PostMapping("/home")
    public ResponseInfo home(){
        List<Map<String,Object>> designDtoList = designRep.homeMap();
        return r.sd(designDtoList);
    }
    /***
     * 文章
     * @return
     */
    @PostMapping("/article")
    public ResponseInfo article(String id){
        ArticleDto articleDto = articleRep.getArticle(Integer.parseInt(id));
        if(articleDto!=null){
            return r.sd(articleDto);
        }else{
            return r.f("文章不存在");
        }
    }
    /***
     * 首页数据
     * @return
     */
    @PostMapping("/index")
    public ResponseInfo index(){
        JSONObject data = new JSONObject();
        //轮播图
        List<SwiperDto> SwiperDtoList = swiperRep.findData();
        List<MenuDto> menuDtoListList = menuRep.findData();
        data.put("swiper",SwiperDtoList);
        data.put("menu",menuDtoListList);
        data.put("line",1);
        data.put("many",4);
        data.put("hotPhone","15225687370");
        List<DesignDto> designDtoList = designRep.indexMap();
        data.put("dataList",designDtoList);
        return r.sd(data);
    }

    /***
     * 商品列表
     * @return
     */
    @PostMapping("/goodsList")
    public ResponseInfo goodsList(){
        if(!isOnle()){
            List<Map<String, Object>> goodsList = goodsRep.findListByASC(0);
            return r.sd(goodsList);
        }
        UserDto user = getUser();
        if(user!=null){
            List<Map<String, Object>> goodsList = goodsRep.findListByASC(user.getLevel());
            return r.sd(goodsList);
        }else{
            List<Map<String, Object>> goodsList = goodsRep.findListByASC(0);
            return r.sd(goodsList);
        }
    }
    /***
     * 查看商品
     * @param id
     * @return
     */
    @PostMapping("/goods")
    public ResponseInfo goods(Integer id){
        if(!isOnle()){
            GoodsDto goodsDto = goodsRep.findGoods(id,0);
            if(goodsDto==null){
                return r.f("商品信息错误");
            }
            return r.sd(goodsDto);
        }
        UserDto user = getUser();
        if(user!=null){
            GoodsDto goodsDto = goodsRep.findGoods(id,user.getLevel());
            if(goodsDto==null){
                return r.f("商品信息错误");
            }
            return r.sd(goodsDto);
        }else{
            GoodsDto goodsDto = goodsRep.findGoods(id,0);
            if(goodsDto==null){
                return r.f("商品信息错误");
            }
            return r.sd(goodsDto);
        }
    }
    /***
     * 收益统计
     * @return
     */
    @PostMapping("/shouYi")
    public ResponseInfo shouYi(){
        if(!isOnle()){
            return r.t();
        }
        UserDto user = getUser();
        if(user!=null){
            Map<String,Object> data = moneyLogRep.findShouYi(user.getId());
            return r.sd(data);
        }else{
            return r.f("请稍后再试！");
        }
    }


    /***
     * 获取等级信息
     * @param userDto
     * @return
     */
    public Map<String,UserDto> getLevelList(UserDto userDto){
        UserDto angel = null;//天使
        UserDto city = null;//市代
        UserDto province = null;//省代
        UserDto province2 = null;//省代
        UserDto partner = null;//分公司
        UserDto partner2 = null;//分公司

        Map<String,UserDto> list = new HashMap<>();
        list.put("angel",angel);
        list.put("city",city);
        list.put("province",province);
        list.put("province2",province2);
        list.put("partner",partner);
        list.put("partner2",partner2);


        Integer level = 0;
        Integer id = userDto.getId();

        while (true){
            Map<String,Object> one = relationRep.findUpById(id);
            if(!one.isEmpty()){
                id = Integer.parseInt(one.get("id").toString());
                level = Integer.parseInt(one.get("level").toString());
                if(level==4){
                    if(partner==null){
                        partner = userRep.findUserById(id);
                        list.put("partner",partner);
                        continue;
                    }else{
                        if(partner2==null){
                            partner2 = userRep.findUserById(id);
                            list.put("partner2",partner2);
                            return list;
                        }
                    }
                }
                if(level==3){
                    if(partner!=null||partner2!=null){
                        continue;
                    }else{
                        if(province==null){
                            province = userRep.findUserById(id);
                            list.put("province",province);
                            continue;
                        }else{
                            if(province2==null){
                                province2 = userRep.findUserById(id);
                                list.put("province2",province2);
                            }else{
                                continue;
                            }
                        }
                    }
                }
                if(level==2){
                    if(partner!=null||partner2!=null||province!=null||province2!=null){
                        continue;
                    }else{
                        if(city==null){
                            city = userRep.findUserById(id);
                            list.put("city",city);
                            continue;
                        }else {
                            continue;
                        }
                    }

                }
                if(level==1){
                    if(partner!=null||partner2!=null||province!=null||province2!=null||city!=null){
                        continue;
                    }else{
                        if(angel==null){
                            angel = userRep.findUserById(id);
                            list.put("angel",angel);
                            continue;
                        }else {
                            continue;
                        }
                    }

                }

            }else{
                return list;
            }
        }
    };


    /***
     * 查找某人指定级别的上级信息
     * @param userDto
     * @param level
     * @return
     */
    public UserDto getUid(UserDto userDto,Integer level){
        Integer le = 0;
        Integer id = userDto.getId();
        while ((le-level)!=0){
            Map<String,Object> one = relationRep.findUpById(id);
            if(!one.isEmpty()){
                id = Integer.parseInt(one.get("id").toString());
                le = Integer.parseInt(one.get("level").toString());
            }else{
                return null;
            }
        }
        return userRep.findUserById(id);
    };

//    JSONObject name1 = new JSONObject();
//                        name1.put("value",teamUserDto.getNick());
//                        data.put("name1",name1);
//
//    JSONObject thing3 = new JSONObject();
//                        thing3.put("value","管理员已允许您参与项目，请尽快前往查看");
//                        data.put("thing3",thing3);
//
//    JSONObject time4 = new JSONObject();
//                        time4.put("value",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
//                        data.put("time4",time4);
//
//    JSONObject thing5 = new JSONObject();
//                        thing5.put("value","点击即可参与项目");
//                        data.put("thing5",thing5);
//
//    UserDto userDto = userRep.getOne(userId);
//                        if(userDto!=null){
//        WXuserinfo(userDto.getOpenid(),"pages/index/index",data);
//    }
    /***
     * 购买升级
     * @param userDto
     */
    public void UpLevel(UserDto userDto){
        Map<String,Object> one = relationRep.findUpById(userDto.getId());
        if(!one.isEmpty()) {
            /*****
             * 在此处理等级晋升
             */
            Integer id = Integer.parseInt(one.get("id").toString());
            Integer level = Integer.parseInt(one.get("level").toString());

            //上级增加推荐天使
            RankDto levelLog = rankRep.getOneByUid(id);
            levelLog.setDl(levelLog.getDl()+1);
            rankRep.save(levelLog);


            //如果上级为天使 且新增了三个天使 则上级升级市代
            if(levelLog.getDl()==3&&level==1){
                UserDto user = userRep.findUserById(id);
                user.setLevel(2);
                userRep.save(user);

                //如果上级的上级为
                Map<String,Object> two = relationRep.findUpById(id);
                if(!two.isEmpty()){

                    Integer id2 = Integer.parseInt(two.get("id").toString());
                    Integer level2 = Integer.parseInt(two.get("level").toString());

                    RankDto levelLog2 = rankRep.getOneByUid(id2);
                    levelLog2.setJl(levelLog2.getJl()+1);
                    rankRep.save(levelLog2);

                    //市代晋升省代
                    if(levelLog2.getJl()==3&&level2==2){

                        UserDto user2 = userRep.findUserById(id2);
                        user2.setLevel(3);
                        userRep.save(user2);

                        //找省代上级
                        Map<String,Object> three = relationRep.findUpById(id2);
                        if(!three.isEmpty()){
                            Integer id3 = Integer.parseInt(three.get("id").toString());
                            Integer level3 = Integer.parseInt(three.get("level").toString());

                            RankDto levelLog3 = rankRep.getOneByUid(id3);
                            levelLog3.setZj(levelLog3.getZj()+1);
                            rankRep.save(levelLog3);

                            //省代晋升战略合伙人
                            if(levelLog3.getZj()==6&&level3==3){
                                UserDto threeUp =  userRep.findUserById(id3);
                                threeUp.setLevel(4);
                                userRep.save(threeUp);
                            }
                        }
                    }
                }
            }
        }
    };

    /***
     * 消费记录
     * @param money
     * @param uid
     * @param sid
     * @param remake
     */
    public void moneyLog(double money,UserDto uid,Integer sid,String remake){
        if(money>0d){
            MoneyLogDto moneyLogDto = new MoneyLogDto();
            moneyLogDto.setMoney(money);
            moneyLogDto.setUserId(uid.getId());
            moneyLogDto.setType(3);//收入
            moneyLogDto.setCreatTime(new Date());
            moneyLogDto.setRemarks(remake);
            moneyLogDto.setSid(sid);
            moneyLogRep.save(moneyLogDto);

            uid.setMoney(uid.getMoney()+money);
            userRep.save(uid);
        }
    }
    /***
     * 返佣
     * @param userDto
     * @param goodsDto
     * @param ordersDto
     */
    public void updateUser(UserDto userDto,GoodsDto goodsDto,OrdersDto ordersDto){
        if(userDto.getLevel()==0){
            System.out.println(userDto.getName()+"会员等级："+userDto.getLevel());
            userDto.setLevel(1);
            userRep.save(userDto);
            System.out.println(userDto.getName()+"升级至："+userDto.getLevel());

            //返佣备注
            String remake = "会员：" + userDto.getName() + " 手机号：" + userDto.getPhone() + " 购买【" + goodsDto.getGoodsName() + "】，订单编号：" + ordersDto.getId();

            //找会员上级
            Map<String,Object> one = relationRep.findUpById(userDto.getId());
            if(!one.isEmpty()) {
                /****
                 * 在此处理返佣
                 */
                Map<String,UserDto> levelMap =  getLevelList(userDto);
                UserDto angel = levelMap.get("angel");
                UserDto city = levelMap.get("city");
                UserDto province = levelMap.get("province");
                UserDto province2 = levelMap.get("province2");
                UserDto partner = levelMap.get("partner");
                UserDto partner2 = levelMap.get("partner2");


                if(angel!=null){
                    System.out.println("天使："+angel.getName());
                }else {
                    System.out.println("天使：无天使");
                }
                if(city!=null){
                    System.out.println("市代："+city.getName());
                }else {
                    System.out.println("市代：无市代");
                }

                if(province!=null){
                    System.out.println("省代："+province.getName());
                    if(province2!=null){
                        System.out.println("省代2："+province2.getName());
                    }else{
                        System.out.println("省代2：无二级省代");
                    }
                }else {
                    System.out.println("省代：无省代");
                }

                if(partner!=null){
                    System.out.println("分公司："+partner.getName());
                    if(partner2!=null){
                        System.out.println("分公司2："+partner2.getName());
                    }else{
                        System.out.println("分公司：无分公司2");
                    }
                }else {
                    System.out.println("分公司：无分公司");
                }

                //战略合伙人直推天使返点10000积分
                if(angel==null&&city==null&&province==null){
                    if (partner != null) {
                        System.out.println("模式一：分公司=>天使");

                        moneyLog(11200d,partner,userDto.getId(),remake);
                        System.out.println(partner.getName()+"->分公司:11200元");

                        if(partner2!=null){//1.分公司直推天使，分公司11200元
                            moneyLog(400d,partner2,userDto.getId(),remake);
                            System.out.println(partner2.getName()+"->分公司2：400元");
                        }
                        UpLevel(userDto);//处理升级
                        return;
                    }else {
                        System.out.println("无模式：系统收益");

                        MoneyLogDto moneyLogDto = new MoneyLogDto();
                        moneyLogDto.setMoney(4000d);
                        moneyLogDto.setUserId(0);
                        moneyLogDto.setType(4);//系统收益
                        moneyLogDto.setCreatTime(new Date());
                        moneyLogDto.setRemarks("会员：" + userDto.getName() + " 手机号：" + userDto.getPhone() + " 购买【" + goodsDto.getGoodsName() + "】，订单编号：" + ordersDto.getId());
                        moneyLogDto.setSid(userDto.getId());
                        moneyLogRep.save(moneyLogDto);
                        System.out.println("会员：" + userDto.getName() + " 手机号：" + userDto.getPhone() + " 会员购买商品，无上级代理，收益归系统");
                        UpLevel(userDto);//处理升级
                        return;
                    }
                }
                //省代直推天使
                if(angel==null&&city==null){
                    if (province != null) {

                        System.out.println("模式二：省代=>天使");
                        moneyLog(10000d,province,userDto.getId(),remake);
                        System.out.println(province.getName()+"->省代:10000元");


                        if(province2!=null){

                            moneyLog(400d,province2,userDto.getId(),remake);
                            System.out.println(province2.getName()+"->省代2:400元");

                            if(partner!=null){

                                moneyLog(800d,partner,userDto.getId(),remake);
                                System.out.println(partner.getName()+"->分公司:800元");

                                if(partner2!=null){
                                    moneyLog(400d,partner2,userDto.getId(),remake);
                                    System.out.println(partner2.getName()+"->分公司2:400元");
                                }
                            }

                            UpLevel(userDto);//处理升级
                            return;
                        }else{

                            if(partner!=null){
                                moneyLog(1200d,partner,userDto.getId(),remake);
                                System.out.println(partner.getName()+"->分公司:1200元");

                                if(partner2!=null){
                                    moneyLog(400d,partner2,userDto.getId(),remake);
                                    System.out.println(partner2.getName()+"->分公司2:400元");
                                }
                            }

                            UpLevel(userDto);//处理升级
                            return;
                        }
                    }
                }
                //市代直推天使
                if(angel==null&&province==null){
                    if (city != null) {//市代直推天使
                        System.out.println("模式三：市代=>天使");
                        moneyLog(7500d,city,userDto.getId(),remake);
                        System.out.println(city.getName()+"->市代:7500元");
                    }
                    if (partner != null) {

                        moneyLog(3700d,partner,userDto.getId(),remake);
                        System.out.println(partner.getName()+"->分公司:3700元");

                        if(partner2!=null){//
                            moneyLog(400d,partner2,userDto.getId(),remake);
                            System.out.println(partner2.getName()+"->分公司2：400元");
                        }
                    }
                    UpLevel(userDto);//处理升级
                    return;
                }
                //天使直推分公司
                if(city==null&&province==null){
                    if (angel != null) {//天使直推天使
                        System.out.println("模式四：天使=>天使");
                        moneyLog(5000d,angel,userDto.getId(),remake);
                        System.out.println(angel.getName()+"->天使:5000元");
                    }
                    if (partner != null) {

                        moneyLog(6200d,partner,userDto.getId(),remake);
                        System.out.println(partner.getName()+"->分公司:6200元");

                        if(partner2!=null){//
                            moneyLog(400d,partner2,userDto.getId(),remake);
                            System.out.println(partner2.getName()+"->分公司2：400元");
                        }
                    }
                    UpLevel(userDto);//处理升级
                    return;
                }


                if(angel!=null&&city!=null&&province==null){//天使、市代、分公司

                    System.out.println("模式五：天使-市代=>天使");

                    moneyLog(5000d,angel,userDto.getId(),remake);
                    System.out.println(angel.getName()+"->天使:5000元");

                    moneyLog(2500d,city,userDto.getId(),remake);
                    System.out.println(city.getName()+"->市代:2500元");


                    if (partner != null) {
                        moneyLog(3700d,partner,userDto.getId(),remake);
                        System.out.println(partner.getName()+"->分公司:3700元");

                        if(partner2!=null){//
                            moneyLog(400d,partner2,userDto.getId(),remake);
                            System.out.println(partner2.getName()+"->分公司2：400元");
                        }
                    }
                    UpLevel(userDto);//处理升级
                    return;
                }


                if(angel!=null&&province!=null&&city==null){//天使、省代、分公司

                    System.out.println("模式六：天使-省代=>天使");

                    moneyLog(5000d,angel,userDto.getId(),remake);
                    System.out.println(angel.getName()+"->天使:5000元");


                    moneyLog(5000d,province,userDto.getId(),remake);
                    System.out.println(province.getName()+"->省代:5000元");


                    if(province2!=null){

                        moneyLog(400d,province2,userDto.getId(),remake);
                        System.out.println(province2.getName()+"->省代2:400元");

                        if(partner!=null){

                            moneyLog(800d,partner,userDto.getId(),remake);
                            System.out.println(partner.getName()+"->分公司:800元");

                            if(partner2!=null){
                                moneyLog(400d,partner2,userDto.getId(),remake);
                                System.out.println(partner2.getName()+"->分公司2:400元");
                            }
                        }

                    }

                    if(partner!=null){

                        moneyLog(1200d,partner,userDto.getId(),remake);
                        System.out.println(partner.getName()+"->分公司:1200元");

                        if(partner2!=null){
                            moneyLog(400d,partner2,userDto.getId(),remake);
                            System.out.println(partner2.getName()+"->分公司2:400元");
                        }
                    }

                    UpLevel(userDto);//处理升级
                    return;
                }

                if(angel!=null&&city!=null&&province!=null){//天使、市代、省代、分公司


                    System.out.println("模式七：天使-市代-省代=>天使");

                    moneyLog(5000d,angel,userDto.getId(),remake);
                    System.out.println(angel.getName()+"->天使:5000元");

                    moneyLog(2500d,city,userDto.getId(),remake);
                    System.out.println(city.getName()+"->市代:2500元");

                    moneyLog(2500d,province,userDto.getId(),remake);
                    System.out.println(province.getName()+"->省代:2500元");


                    if(province2!=null){

                        moneyLog(400d,province2,userDto.getId(),remake);
                        System.out.println(province2.getName()+"->省代2:400元");

                        if(partner!=null){

                            moneyLog(800d,partner,userDto.getId(),remake);
                            System.out.println(partner.getName()+"->分公司:800元");

                            if(partner2!=null){
                                moneyLog(400d,partner2,userDto.getId(),remake);
                                System.out.println(partner2.getName()+"->分公司2:400元");
                            }
                        }
                        UpLevel(userDto);//处理升级
                        return;
                    }

                    if(partner!=null){

                        moneyLog(1200d,partner,userDto.getId(),remake);
                        System.out.println(partner.getName()+"->分公司:1200元");

                        if(partner2!=null){
                            moneyLog(400d,partner2,userDto.getId(),remake);
                            System.out.println(partner2.getName()+"->分公司2:400元");
                        }
                    }

                    UpLevel(userDto);//处理升级
                    return;
                }
                if(angel==null&&city!=null&&province!=null){//天使、市代、省代、分公司


                    System.out.println("模式八：市代-省代=>天使");


                    moneyLog(7500d,city,userDto.getId(),remake);
                    System.out.println(city.getName()+"->市代:7500元");

                    moneyLog(2500d,province,userDto.getId(),remake);
                    System.out.println(province.getName()+"->省代:2500元");


                    if(province2!=null){

                        moneyLog(400d,province2,userDto.getId(),remake);
                        System.out.println(province2.getName()+"->省代2:400元");

                        if(partner!=null){

                            moneyLog(800d,partner,userDto.getId(),remake);
                            System.out.println(partner.getName()+"->分公司:800元");

                            if(partner2!=null){
                                moneyLog(400d,partner2,userDto.getId(),remake);
                                System.out.println(partner2.getName()+"->分公司2:400元");
                            }
                        }
                        UpLevel(userDto);//处理升级
                        return;
                    }

                    if(partner!=null){

                        moneyLog(1200d,partner,userDto.getId(),remake);
                        System.out.println(partner.getName()+"->分公司:1200元");

                        if(partner2!=null){
                            moneyLog(400d,partner2,userDto.getId(),remake);
                            System.out.println(partner2.getName()+"->分公司2:400元");
                        }
                    }

                    UpLevel(userDto);//处理升级
                    return;
                }
            }
        }
    }
    /***
     * 查看二级人员信息
     * @param id
     * @return
     */
    @PostMapping("/memberTwo")
    public ResponseInfo memberTwo(Integer id){
        if(!isOnle()){
            return r.t();
        }
        UserDto user = getUser();
        if(user!=null){
            JSONObject data = new JSONObject();
            UserDto uid = userRep.findUserById(id);
            if(uid!=null){

                data.put("money",uid.getMoney());
                data.put("head",uid.getHead());
                data.put("level",level(uid.getLevel()));
                data.put("name",uid.getName());

                List<Map<String,Object>> memberList = new ArrayList<>();
                memberList = relationRep.getTwoMember(uid.getId());
                data.put("num",memberList.size());
                data.put("memberList",memberList);
                return r.sd(data);
            }else{
                return r.f("人员信息错误");
            }
        }else{
            return r.f();
        }
    }

    /***
     * 核销
     * @param id
     * @param name
     * @param tel
     * @param remake
     * @return
     */
    @PostMapping("/hexiao")
    public ResponseInfo hexiao(Integer id,String name,String tel,String remake){
        if(!isOnle()){
            return r.t();
        }
        UserDto user = getUser();
        if(user!=null){
            if(user.getIsAdmin()!=1){
                return r.f("暂无权限");
            }
            StudyCodeDto studyCodeDto = studyCodeRep.getOne(id);
            if(studyCodeDto!=null){
                if(studyCodeDto.getState()==1){
                    return r.f("核销失败，该学习码已被核销");
                }
                studyCodeDto.setUName(name);
                studyCodeDto.setUTel(tel);
                studyCodeDto.setRemake(remake);
                studyCodeDto.setState(1);
                studyCodeRep.save(studyCodeDto);
                return r.s();
            }else{
                return r.f("学习码无效");
            }
        }else{
            return r.t();
        }
    }
    /***
     * 扫描学习码
     * @return
     */
    @PostMapping("/scanCode")
    public ResponseInfo scanCode(String code){
        if(!isOnle()){
            return r.t();
        }
        UserDto user = getUser();
        if(user!=null){
            if(user.getIsAdmin()!=1){
                return r.f("暂无权限");
            }
            StudyCodeDto studyCodeDto = studyCodeRep.getCode(code);
            if(studyCodeDto!=null){
                return r.sd(studyCodeDto);
            }else{
                return r.f("学习码无效");
            }

        }else{
            return r.t();
        }
    }
    /***
     * 获取我的学习码
     * @return
     */
    @PostMapping("/getStudyCode")
     public ResponseInfo getCode(){
        if(!isOnle()){
            return r.t();
        }
        UserDto user = getUser();
        if(user!=null){
            List<StudyCodeDto> codeDtoList = studyCodeRep.getListByUid(user.getId());
            return r.sd(codeDtoList);
        }else{
            return r.t();
        }
    }



    /***
     * 转赠学习码
     * @param name
     * @param phone
     * @param id
     * @param pwd
     * @return
     */
    @PostMapping("/zeng")
    public ResponseInfo zeng(String name,String phone,Integer id,String pwd){
        if(!isOnle()){
            return r.t();
        }
        UserDto user= getUser();
        if(user!=null){
            if(user.getPayPwd().equals(pwd)){
                UserDto pid = userRep.findUpUser(name,phone);
                if(pid==null){
                    return  r.f("请重新确认对方姓名及手机号");
                }else{
                    StudyCodeDto studyCodeDto = studyCodeRep.getOne(id);
                    if(studyCodeDto==null){
                        return r.f("当前学习码无效");
                    }else{
                        if(studyCodeDto.getState()==1){
                            return r.f("转赠失败，学习码已使用");
                        }else{
                            if(studyCodeDto.getIsGive()==0){
                                studyCodeDto.setUid(pid.getId());
                                studyCodeDto.setIsGive(1);
                                studyCodeDto.setBody(user.getName()+" 赠送");


                                studyCodeDto.setUName(pid.getName());
                                studyCodeDto.setUTel(pid.getPhone());

                                studyCodeRep.save(studyCodeDto);



                                if(pid.getOpenid()!=null){
                                    JSONObject data = new JSONObject();
                                    JSONObject name1 = new JSONObject();
                                    name1.put("value",pid.getName());
                                    data.put("name1",name1);

                                    JSONObject thing3 = new JSONObject();
                                    thing3.put("value",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                    data.put("date4",thing3);

                                    JSONObject time4 = new JSONObject();
                                    time4.put("value","来自"+user.getName());
                                    data.put("thing5",time4);


                                    JSONObject date4 = new JSONObject();
                                    date4.put("value","学习码");
                                    data.put("thing2",date4);
                                    WxTempMsg.sendMsg(pid.getOpenid(),"/pages/me/studyCode/studyCode",data,"Ebg2wxw1Gt5xMVnWfLI7C8QoKfhwdsiulPmeX9ZsEDU");
                                }


                                return r.s("转赠成功");
                            }else{
                                return r.f("该学习码禁止转赠");
                            }
                        }
                    }
                }
            }else{
                return r.f("密码错误");
            }
        }
        return r.f();
    }

    /**
     * 查看我的团队人员信息（一级）
     * @return
     */
    @PostMapping("/member")
    public ResponseInfo member(){
        if(!isOnle()){
            return r.t();
        }
        UserDto user = getUser();
        if(user!=null){
            JSONObject data = new JSONObject();

            data.put("money",user.getMoney());
            data.put("head",user.getHead());
            data.put("level",level(user.getLevel()));
            data.put("name",user.getName());

            List<Map<String,Object>> memberList = new ArrayList<>();
            memberList = relationRep.getOneMember(user.getId());
            data.put("num",memberList.size());
            data.put("memberList",memberList);
            return r.sd(data);
        }else{
            return r.f();
        }
    }

    /***
     * 查看积分
     * @param type 0 所有 1当日收益 2本月收益 3 累计收益
     * @param page
     * @return
     */
    @PostMapping("/moneyLog")
    public ResponseInfo moneyLog(Integer type,String page){
        if(!isOnle()){
            return r.t();
        }
        UserDto user = getUser();
        if(user!=null){
            Page pages = new Page();
            pages.setCurrentPage(Integer.parseInt(page));
            pages.setPerPageRows(1000);
            String sql = "";
            if(type==0){
                sql = " SELECT * FROM money_log WHERE user_id = " +user.getId()+" ORDER BY id desc ";
            }else if(type==1){
                sql = " SELECT * FROM money_log WHERE user_id = " +user.getId()+" AND type = 3  ORDER BY id desc ";
            }else if(type==2){
                sql = " SELECT * FROM money_log WHERE user_id = " +user.getId()+" AND type = 1 ORDER BY id desc ";
            }else if(type==3){
                sql = " SELECT * FROM money_log WHERE user_id = " +user.getId()+" AND type = 2 ORDER BY id desc ";
            }else if(type==4){
                sql = " SELECT * FROM money_log WHERE user_id = " +user.getId()+" AND type = 0 ORDER BY id desc ";
            }
            Query dataQuery = entityManager.createNativeQuery(sql,MoneyLogDto.class);

            //1 红包支出  2红包收入  3第三方充值 4 提现支出
            Double income = 0d;
            Double expenditure = 0d;
            Double hb = 0d;
            Double fy = 0d;
            List<MoneyLogDto> moneyLogDtoList = dataQuery.getResultList();
            for(MoneyLogDto mb:moneyLogDtoList){
                if(mb.getType()==0){//充值
                    income = income+mb.getMoney();
                }else if(mb.getType()==1){//支出
                    expenditure = expenditure+mb.getMoney();
                }else if(mb.getType()==2){//划拨
                    hb = hb+mb.getMoney();
                }else if(mb.getType()==3){//返佣
                    fy = fy+mb.getMoney();
                }
            }

            Integer totalRows = dataQuery.getResultList().size();
            pages.setTotalRows(totalRows);//设置总数量

            Integer currentPage = pages.getCurrentPage();//得到当前页
            Integer perPageRows = pages.getPerPageRows();//得到每页的记录数：

            dataQuery.setFirstResult((currentPage-1)*perPageRows);
            dataQuery.setMaxResults(perPageRows);

            int s = totalRows/1000;
            int y = totalRows%1000;
            pages.setTotalPages(s);
            if(y>0){
                pages.setTotalPages(s+1);
            }


            pages.setPageData(dataQuery.getResultList());
            pages.setIncome(income);
            pages.setExpenditure(expenditure);
            pages.setHuaBo(hb);
            pages.setFanYong(fy);
            return r.sd(pages);
        }else{
            return r.f();
        }
    }

    /***
     * 查看订单详情
     * @param id
     * @return
     */
    @PostMapping("/lookOrder")
    public ResponseInfo lookOrder(Integer id){
        if(!isOnle()){
            return r.t();
        }
        UserDto user = getUser();
        if(user!=null){
            Map<String, Object> ordersDto = ordersRep.findOrdersMap(user.getId(),id.toString());
            return r.sd(ordersDto);
        }else{
            return r.f();
        }
    }
    /***
     * 确认收货
     * @param pwd 支付密码
     * @param id 订单号
     * @return
     */
    @PostMapping("/confirmOrders")
    public ResponseInfo confirmOrders(String pwd,String id){
        if(!isOnle()){
            return r.t();
        }
        UserDto user = getUser();
        if(user!=null){
            if(user.getPayPwd().equals(pwd)){
                OrdersDto ordersDto = ordersRep.findOrders(user.getId(),id);
                if(ordersDto==null){
                    return r.f("订单不存在！");
                }else{
                    if(ordersDto.getState()==1){
                        ordersDto.setState(2);
                        ordersRep.save(ordersDto);
                        return r.s("订单已完成收货");
                    }else{
                        return r.f("暂时不能确认收货");
                    }
                }
            }else{
                return r.f("支付密码错误");
            }
        }else{
            return r.f();
        }
    }
    /***
     * 查看订单
     * @param type 0 待发货 1 待收货 2 已完成
     * @param page
     * @return
     */
    @PostMapping("/orders")
    public ResponseInfo orders(String type,String page){
        if(!isOnle()){
            return r.t();
        }
        UserDto user = getUser();
        if(user!=null){
            Page pages = new Page();
            pages.setCurrentPage(Integer.parseInt(page));
            pages.setPerPageRows(20);
            String sql = " SELECT * FROM orders WHERE user_id = " +user.getId()+" AND state = "+type +" ORDER BY id desc ";
            Query dataQuery = entityManager.createNativeQuery(sql,OrdersDto.class);

            Integer totalRows = dataQuery.getResultList().size();
            pages.setTotalRows(totalRows);//设置总数量

            Integer currentPage = pages.getCurrentPage();//得到当前页
            Integer perPageRows = pages.getPerPageRows();//得到每页的记录数：

            dataQuery.setFirstResult((currentPage-1)*perPageRows);
            dataQuery.setMaxResults(perPageRows);

            int s = totalRows/20;
            int y = totalRows%20;
            pages.setTotalPages(s);
            if(y>0){
                pages.setTotalPages(s+1);
            }
            //1 红包支出  2红包收入  3第三方充值 4 提现支出
            Double income = 0d;
            Double expenditure = 0d;
            List<OrdersDto> orderDtoList = dataQuery.getResultList();

            pages.setPageData(dataQuery.getResultList());
            return r.sd(pages);
        }else{
            return r.f();
        }
    }


    /***
     * 购买商品
     * @param id
     * @return
     */
    @PostMapping("/buy")
    public ResponseInfo buy(String pwd,String id,Integer addressId){
        if(!isOnle()){
            return r.t();
        }
        UserDto user= getUser();
        if(user!=null){
            if(user.getIsUp()==0){
                return r.f("请绑定上级");
            }
            GoodsDto goodsDto = goodsRep.getOne(Integer.parseInt(id));
            if(goodsDto==null){
                return r.f("商品信息错误");
            }
            Map<String,Object> addressDto = addressRep.findAddressById(user.getId(),addressId);
            if(addressDto.isEmpty()){
                return r.f("收货人信息错误");
            }
            if(user.getPayPwd().equals(pwd)){
                if(user.getMoney()-goodsDto.getGoodsPrices()<0){
                    return r.f("积分不足，购买失败");
                }
                //扣款
                user.setMoney(user.getMoney()-goodsDto.getGoodsPrices());
                userRep.save(user);

                //消费记录
                MoneyLogDto moneyLogDto = new MoneyLogDto();
                moneyLogDto.setUserId(user.getId());
                moneyLogDto.setMoney(goodsDto.getGoodsPrices());
                moneyLogDto.setType(1);//支出
                moneyLogDto.setRemarks("购买"+goodsDto.getGoodsName());
                moneyLogDto.setCreatTime(new Date());
                moneyLogRep.save(moneyLogDto);

                //订单
                OrdersDto ordersDto = new OrdersDto();
                ordersDto.setIsOld(0);
                ordersDto.setUserId(user.getId());
                ordersDto.setGoodsId(Integer.parseInt(id));
                ordersDto.setGoodsPrice(goodsDto.getGoodsPrices());
                ordersDto.setGoodsTitle(goodsDto.getGoodsName());
                String image[] = goodsDto.getGoodsSwiper().replaceAll("\\[","").replaceAll("\\]","").replaceAll("\"","").split(",");
                ordersDto.setGoodsImage(image[0]);
                ordersDto.setState(0);
                ordersDto.setCreatTime(new Date());
                ordersDto.setFreight(0d);


//                JSONArray orderInfo = new JSONArray();
//                JSONObject info = new JSONObject();
//                info.put("uid",ordersDto.getId());
//                info.put("gid",goodsDto.getId());
//                info.put("title",goodsDto.getGoodsName());
//                info.put("price",goodsDto.getGoodsPrices());
//                info.put("img",image[0]);
//                info.put("num",1);
//                info.put("goodsPrice",goodsDto.getGoodsPrices());
//                info.put("priceAngel",1*goodsDto.getPriceAngel());
//                info.put("priceCity",1*goodsDto.getPriceCity());
//                info.put("priceProvince",1*goodsDto.getPriceProvince());
//                info.put("pricePartner",1*goodsDto.getPricePartner());
//                orderInfo.add(info);
//                ordersDto.setOrderInfo(orderInfo.toString());

                ordersDto.setUname(addressDto.get("name").toString());
                ordersDto.setUphone(addressDto.get("phone").toString());
                ordersDto.setUaddress(addressDto.get("province").toString()+addressDto.get("city").toString()+addressDto.get("area").toString()+addressDto.get("address").toString());
                //TODO:赠送礼包
                ordersRep.save(ordersDto);
               for(int i=0;i<2;i++){
                   String code_str = getName("STUDY");
                   StudyCodeDto studyCodeDto = new StudyCodeDto();
                   studyCodeDto.setBody("2万元创业礼包赠送");
                   studyCodeDto.setIsGive(0);
                   studyCodeDto.setState(0);
                   studyCodeDto.setUid(user.getId());
                   studyCodeDto.setOid(ordersDto.getId());
                   studyCodeDto.setUName(user.getName());
                   studyCodeDto.setUTel(user.getPhone());



                   try {
                       studyCodeDto.setQrCode(QRCodeUtil.encode(code_str));
                       studyCodeDto.setCodeStr(code_str);
                   } catch (WriterException e) {
                       e.printStackTrace();
                   } catch (IOException e) {
                       e.printStackTrace();
                   }
                   studyCodeRep.save(studyCodeDto);
               }
                //处理等级关系，以及分销细信息
                updateUser(user,goodsDto,ordersDto);
                return r.s();
            }else{
                return r.f("支付密码错误");
            }
        }
        return r.f();
    }

    /***
     * 购物车结算
     * @param Order
     * @return
     */
    @PostMapping("/carBuy")
    public ResponseInfo carBuy(@RequestBody JSONObject Order){
        if(!isOnle()){
            return r.t();
        }
        UserDto user= getUser();
        if(user!=null){
            Map<String,Object> addressDto = addressRep.findAddressById(user.getId(),Order.getInt("addressId"));
            if(addressDto.isEmpty()){
                return r.f("地址信息错误");
            }
            List<JSONObject> carGoodsList = Order.getJSONArray("paymentOrder");
            if(carGoodsList==null){
                return r.f("商品信息错误");
            }
            if(!user.getPayPwd().equals(Order.getString("pwd"))){
                return r.f("支付密码错误");
            }

            Double money = 0d;//商品总积分
            for(JSONObject carGoods:carGoodsList){
                GoodsDto goodsDto = goodsRep.findGoods(carGoods.getInt("id"),user.getLevel());
                if(goodsDto==null){
                    return r.f(carGoods.getString("name")+"商品信息错误，请移除");
                }else{
                    money = money+(goodsDto.getGoodsPrices()*carGoods.getInt("number"));
                }
            }

            double freight =  Double.valueOf(addressDto.get("freight").toString());
            money = money+freight;

            //计算积分是否够用
            if(user.getMoney()-money<0){
                return r.f("积分不足，购物车商品购买失败");
            }
            //扣款

            user.setMoney(user.getMoney()-money);
            userRep.save(user);


            //先生成订单
            OrdersDto ordersDto = new OrdersDto();

            ordersDto.setUserId(user.getId());
            ordersDto.setGoodsId(0);
            ordersDto.setGoodsPrice(0d);
            ordersDto.setGoodsTitle("购物车订单");
            ordersDto.setGoodsImage("");

            ordersDto.setFreight(freight);//运费
            ordersDto.setIsOld(1);//0旧订单逻辑 1 新订单逻辑
            ordersDto.setState(0);
            ordersDto.setCreatTime(new Date());
            ordersDto.setUname(addressDto.get("name").toString());
            ordersDto.setUphone(addressDto.get("phone").toString());
            ordersDto.setUaddress(addressDto.get("province").toString()+addressDto.get("city").toString()+addressDto.get("area").toString()+addressDto.get("address").toString());
            ordersRep.save(ordersDto);

            JSONArray orderInfo = new JSONArray();
            for(JSONObject carGoods:carGoodsList){
                GoodsDto goodsDto = goodsRep.getOne(carGoods.getInt("id"));
                if(goodsDto==null){
                    return r.f(carGoods.getString("name")+"商品信息错误，请移除");
                }else{
                    int num = carGoods.getInt("number");
                    //生成消费记录
                    MoneyLogDto moneyLogDto = new MoneyLogDto();
                    moneyLogDto.setUserId(user.getId());
                    moneyLogDto.setMoney(goodsDto.getGoodsPrices()*num);
                    moneyLogDto.setType(1);//支出
                    moneyLogDto.setRemarks("购买"+goodsDto.getGoodsName()+" X"+num);
                    moneyLogDto.setCreatTime(new Date());
                    moneyLogRep.save(moneyLogDto);
                    //生成订单详情
                    String image[] = goodsDto.getGoodsSwiper().replaceAll("\\[","").replaceAll("\\]","").replaceAll("\"","").split(",");
                    JSONObject info = new JSONObject();
                    info.put("uid",ordersDto.getId());
                    info.put("gid",goodsDto.getId());
                    info.put("title",goodsDto.getGoodsName());
                    info.put("price",goodsDto.getGoodsPrices());
                    info.put("img",image[0]);
                    info.put("num",num);
                    info.put("goodsPrice",goodsDto.getGoodsPrices());
                    info.put("priceAngel",num*goodsDto.getPriceAngel());
                    info.put("priceCity",num*goodsDto.getPriceCity());
                    info.put("priceProvince",num*goodsDto.getPriceProvince());
                    info.put("pricePartner",num*goodsDto.getPricePartner());
                    orderInfo.add(info);

                    OrderInfoDto orderInfoDto = new OrderInfoDto();
                    orderInfoDto.setIsDistribution(1);
                    orderInfoDto.setOid(ordersDto.getId());
                    orderInfoDto.setGid(goodsDto.getId());
                    orderInfoDto.setUid(user.getId());
                    orderInfoDto.setTitle(goodsDto.getGoodsName());
                    orderInfoDto.setPrice(goodsDto.getGoodsPrices());
                    orderInfoDto.setNum(num);

                    orderInfoDto.setImg(image[0]);
                    orderInfoDto.setGoodsPrice(goodsDto.getGoodsPrices());
                    orderInfoDto.setPriceAngel(num*goodsDto.getPriceAngel());//天使返佣
                    orderInfoDto.setPriceCity(num*goodsDto.getPriceCity());//市代返佣
                    orderInfoDto.setPriceProvince(num*goodsDto.getPriceProvince());//省代返佣
                    orderInfoDto.setPricePartner(num*goodsDto.getPricePartner());//合伙人返佣
                    orderInfoRep.save(orderInfoDto);
                    //处理返佣
                    rakeBack(user,info);
                }
            }

            MoneyLogDto moneyLogDto = new MoneyLogDto();
            moneyLogDto.setUserId(user.getId());
            moneyLogDto.setMoney(freight);
            moneyLogDto.setType(1);//支出
            moneyLogDto.setRemarks("订单："+ordersDto.getId()+" 运费");
            moneyLogDto.setCreatTime(new Date());
            moneyLogRep.save(moneyLogDto);


            ordersDto.setOrderInfo(orderInfo.toString());
            ordersRep.save(ordersDto);
            //消息通知
            if(adminOpenId.length>0){
                JSONObject data = new JSONObject();
                JSONObject name1 = new JSONObject();
                name1.put("value",user.getName());
                data.put("name1",name1);

                JSONObject thing3 = new JSONObject();
                thing3.put("value",ordersDto.getId());
                data.put("character_string2",thing3);

                JSONObject time4 = new JSONObject();
                time4.put("value",money);
                data.put("amount3",time4);


                JSONObject date4 = new JSONObject();
                date4.put("value",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                data.put("date4",date4);

                JSONObject thing6 = new JSONObject();
                thing6.put("value","购物车订单");
                data.put("thing6",thing6);
                WxTempMsg.sendMsg(adminOpenId[0],"/pages/index/index",data,"ooSyWmu9B-6lAWwlujygdsOfDb_tRDdG7pX3MyQ4gcI");//下单通知
            }

            //用户提醒

            if(user.getOpenid()!=null){
                JSONObject data = new JSONObject();
                JSONObject name1 = new JSONObject();
                name1.put("value",ordersDto.getId());
                data.put("character_string1",name1);

                JSONObject thing3 = new JSONObject();
                thing3.put("value","待发货");
                data.put("phrase2",thing3);

                JSONObject time4 = new JSONObject();
                time4.put("value","未发货");
                data.put("name3",time4);


                JSONObject date4 = new JSONObject();
                date4.put("value","0000");
                data.put("character_string4",date4);

                JSONObject thing6 = new JSONObject();
                thing6.put("value","发货后更新订单信息");
                data.put("thing5",thing6);
                WxTempMsg.sendMsg(user.getOpenid(),"/pages/me/orders/index?index=0",data,"pjqTDJPO4x-3BnyRgnh3qOahzgb2qPAbSYNKvAHV5jk");
            }
            return r.s(money.toString());
        }
        return r.f();
    }

    /***
     * 购物车返佣
     * @param userDto
     * @param orderInfoDto
     */
    private void rakeBack(UserDto userDto, JSONObject orderInfoDto) {

        String remake = "会员：" + userDto.getName() + " 手机号：" + userDto.getPhone() + " 购买【" + orderInfoDto.getString("title") + "】" ;

        double priceCity = orderInfoDto.getDouble("priceCity");
        double priceProvince = orderInfoDto.getDouble("priceProvince");
        double pricePartner = orderInfoDto.getDouble("pricePartner");

        int level = userDto.getLevel();

        Map<String,UserDto> levelMap =  getLevelList(userDto);
        UserDto angel = levelMap.get("angel");
        UserDto city = levelMap.get("city");
        UserDto province = levelMap.get("province");
        UserDto province2 = levelMap.get("province2");
        UserDto partner = levelMap.get("partner");
        UserDto partner2 = levelMap.get("partner2");

        if(level==1){
//            UserDto city = getUid(userDto, 2);
//            UserDto province = getUid(userDto, 3);
//            UserDto partner = getUid(userDto, 4);

            if(city!=null&&province!=null&&partner!=null){

                moneyLog(priceCity,city,userDto.getId(),remake);
                System.out.println(city.getName()+"->市代:"+priceCity+"元");

                moneyLog(priceProvince,province,userDto.getId(),remake);
                System.out.println(province.getName()+"->省代:"+priceProvince+"元");

                moneyLog(pricePartner,partner,userDto.getId(),remake);
                System.out.println(partner.getName()+"->分公司:"+pricePartner+"元");

            }
            if(city==null&&province!=null&&partner!=null){
                moneyLog((priceProvince+priceCity),province,userDto.getId(),remake);
                System.out.println(province.getName()+"->省代:"+(priceProvince+priceCity)+"元");

                moneyLog(pricePartner,partner,userDto.getId(),remake);
                System.out.println(partner.getName()+"->分公司:"+pricePartner+"元");

            }
            if(city!=null&&province==null&&partner!=null){

                moneyLog(priceCity,city,userDto.getId(),remake);
                System.out.println(city.getName()+"->市代:"+priceCity+"元");


                moneyLog((pricePartner+priceProvince),partner,userDto.getId(),remake);
                System.out.println(partner.getName()+"->分公司:"+(pricePartner+priceProvince)+"元");

            }

            if(city==null&&province==null&&partner!=null){

                moneyLog((pricePartner+priceProvince+priceCity),partner,userDto.getId(),remake);
                System.out.println(partner.getName()+"->分公司:"+(pricePartner+priceProvince+priceCity)+"元");

            }

            return;

        }

        if(level==2){
//            UserDto province = getUid(userDto, 3);
//            UserDto partner = getUid(userDto, 4);

            if(province!=null&&partner!=null){

                moneyLog(priceProvince,province,userDto.getId(),remake);
                System.out.println(province.getName()+"->省代:"+priceProvince+"元");

                moneyLog(pricePartner,partner,userDto.getId(),remake);
                System.out.println(partner.getName()+"->分公司:"+pricePartner+"元");

            }
            if(province==null&&partner!=null){
                moneyLog((pricePartner+priceProvince),partner,userDto.getId(),remake);
                System.out.println(partner.getName()+"->分公司:"+(pricePartner+priceProvince)+"元");
            }

            return;
        }
        if(level==3){
//            UserDto partner = getUid(userDto, 4);

            if(partner!=null){
                moneyLog(pricePartner,partner,userDto.getId(),remake);
                System.out.println(partner.getName()+"->分公司:"+pricePartner+"元");
            }
            return;
        }
    }

    /***
     * 积分划拨
     * @param name
     * @param phone
     * @param jiFen
     * @return
     */
    @PostMapping("/transfer")
    public ResponseInfo transfer(String name,String phone,String jiFen,String pwd){
        if(!isOnle()){
            return r.t();
        }
        UserDto user= getUser();
        if(user!=null){
            if(user.getPayPwd().equals(pwd)){
                UserDto pid = userRep.findUpUser(name,phone);
                if(pid==null){
                    return  r.f("请重新确认对方姓名及手机号");
                }else{
                    Double ji = Double.valueOf(jiFen);
                    if(user.getMoney()-ji>=0){
                        pid.setMoney(pid.getMoney()+ji);
                        userRep.save(pid);
                        user.setMoney(user.getMoney()-ji);
                        userRep.save(user);


                        MoneyLogDto moneyLogDto = new MoneyLogDto();
                        moneyLogDto.setUserId(user.getId());
                        moneyLogDto.setMoney(ji);
                        moneyLogDto.setType(2);//划拨
                        moneyLogDto.setRemarks("向会员："+pid.getName()+" 手机号："+pid.getPhone()+" 划拨 "+ji);
                        moneyLogDto.setCreatTime(new Date());
                        moneyLogRep.save(moneyLogDto);


                        MoneyLogDto pMoney = new MoneyLogDto();
                        pMoney.setUserId(pid.getId());
                        pMoney.setMoney(ji);
                        pMoney.setType(0);//收入
                        pMoney.setRemarks("收到会员: "+user.getName()+" 手机号："+ user.getPhone()+" 划拨 "+ji);
                        pMoney.setCreatTime(new Date());
                        moneyLogRep.save(pMoney);



                        if(pid.getOpenid()!=null){
                            JSONObject data = new JSONObject();
                            JSONObject name1 = new JSONObject();
                            name1.put("value","+"+ji);
                            data.put("character_string2",name1);

                            JSONObject thing3 = new JSONObject();
                            thing3.put("value",pid.getMoney().intValue());
                            data.put("number3",thing3);

                            JSONObject time4 = new JSONObject();
                            time4.put("value",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                            data.put("date4",time4);


                            JSONObject date4 = new JSONObject();
                            date4.put("value",user.getName()+"划拨");
                            data.put("thing5",date4);
                            WxTempMsg.sendMsg(pid.getOpenid(),"/pages/me/gift/gift",data,"FcH8-N5I11v3aoWL1uBw4Ve7prezDHioZmpTLLW9O4c");
                        }

                        return r.s();
                    }else {
                      return   r.f("您当前积分不足");
                    }
                }
            }else{
                return r.f("验证错误");
            }

        }
        return r.f();
    }

    /***
     * 绑定上级   需要上级姓名和手机号
     * @param name
     * @param phone
     * @return
     */
    @PostMapping("/bindUp")
    public ResponseInfo bindUp(String name,String phone,String pwd){
        if(!isOnle()){
            return r.t();
        }
        UserDto user= getUser();
        if(user!=null){
            if(user.getPayPwd().equals(pwd)){
                UserDto pid = userRep.findUpUser(name,phone);
                if(pid==null){
                   return r.f("请重新确认上级姓名及手机号");
                }else{
                    pid.setIsDown(1);//上级有下级，运营中心可以显示下级信息
                    user.setIsUp(1);//用户绑定上级，绑定功能不能再使用了
                    //我是我上级的 1
                    RelationDto relation = new RelationDto();
                    relation.setUid(user.getId());
                    relation.setPid(pid.getId());
                    relation.setLevel(1);
                    relationRep.save(relation);
                    System.out.println(pid.getId()+"是"+user.getId()+"的一级");
                    //我是我上级的上级的 2
                    List<Map<String,Integer>> tidList = relationRep.findPid(pid.getId());
                    for(Map<String,Integer> MapTid:tidList){
                        Integer tid = MapTid.get("pid");
                        RelationDto gid = new RelationDto();
                        gid.setUid(user.getId());
                        gid.setPid(tid);
                        gid.setLevel(2);
                        relationRep.save(gid);
                        System.out.println(tid+"是"+user.getId()+"的二级");
                    }

                    //我的下级 是我上级的 2
                    List<Map<String,Integer>> didList = relationRep.findDid(user.getId());
                    for(Map<String,Integer> MapDid:didList){
                        Integer did = MapDid.get("uid");
                        RelationDto didDto = new RelationDto();
                        didDto.setUid(did);
                        didDto.setPid(pid.getId());
                        didDto.setLevel(2);
                        relationRep.save(didDto);
                        System.out.println(did+"是"+pid.getId()+"的二级");
                    }


                    if(pid.getOpenid()!=null){
                        JSONObject data = new JSONObject();
                        JSONObject name1 = new JSONObject();
                        name1.put("value",user.getPhone());
                        data.put("name1",name1);

                        JSONObject time4 = new JSONObject();
                        time4.put("value",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                        data.put("date2",time4);


                        JSONObject thing3 = new JSONObject();
                        thing3.put("value","快去看看你的团队吧~");
                        data.put("thing3",thing3);



                        JSONObject date4 = new JSONObject();
                        date4.put("value",user.getName());
                        data.put("thing4",date4);
                        WxTempMsg.sendMsg(pid.getOpenid(),"/pages/me/people/people",data,"lo_-IurB2JRI61MZIrWBbNxL5UOjWVqFAu82DbKcHac");
                    }

                   return r.s();
                }
            }else{
                return r.f("密码错误，请重新输入");
            }
        }
        return r.f();
    }


    /***
     * 收货地址列表
     * @return
     */
    @PostMapping("/getAddressList")
    public ResponseInfo getAddressList(){
        if(!isOnle()){
            return r.t();
        }
        UserDto user= getUser();
        if(user!=null){
            List<Map<String,String>> addressDtoList = addressRep.findListByUserId(user.getId());
            return  r.sd(addressDtoList);
        }
        return r.f();
    }

    /***
     * 删除地址
     * @param id
     * @return
     */
    @PostMapping("/delAddress")
    public ResponseInfo delAddress(String id){
        if(!isOnle()){
            return r.t();
        }
        UserDto user= getUser();
        if(user!=null){
            AddressDto addressDto = addressRep.getOne(Integer.parseInt(id));
            if(addressDto!=null){
                addressRep.delete(addressDto);
                return r.s();
            }else{
                return r.f("地址信息有误");
            }
        }else{
            return r.t();
        }
    }

    /***
     * 获取默认地址
     * @return
     */
    @PostMapping("/getDefaultAddress")
    public ResponseInfo getDefaultAddress(){
        if(!isOnle()){
            return r.t();
        }
        UserDto user= getUser();
        if(user!=null){
            //AddressDto addressDto = addressRep.getDefaultAddress(user.getId());

            Map<String,Object> addressDto = addressRep.getDefaultAddress(user.getId());

            if(!addressDto.isEmpty()){
                return r.sd(addressDto);
            }else{
                return r.f("暂未设置默认地址");
            }
        }else{
            return r.t();
        }
    }
    /***
     * 根据地址id 查询地址详情
     * @param id
     * @return
     */
    @PostMapping("/getAddress")
    public ResponseInfo getAddress(String id){
        if(!isOnle()){
            return r.t();
        }
        UserDto user= getUser();
        if(user!=null){
            Map<String,Object> addressDto = addressRep.getAddress(user.getId(),Integer.parseInt(id));
            if(!addressDto.isEmpty()){
                return r.sd(addressDto);
            }else{
                return r.f("地址信息有误");
            }
        }else{
            return r.t();
        }
    }

    /***
     * 新增地址
     * @param name
     * @param phone
     * @param province
     * @param city
     * @param area
     * @param address
     * @param isDefault
     * @return
     */
    @PostMapping("/addAddress")
        public ResponseInfo addAddress(String name,String phone,String province,String city,String area,String address,String isDefault){
        if(!isOnle()){
            return r.t();
        }
        UserDto user= getUser();
        if(user!=null){
            if(isDefault.equals("1")){
                AddressDto AddressDto = addressRep.findByUserIdDefault(user.getId());
                if(AddressDto!=null){
                    AddressDto.setIsDefault(0);
                    addressRep.save(AddressDto);
                }
            }
            AddressDto addres = new AddressDto();
            addres.setUserId(user.getId());
            addres.setName(name);
            addres.setPhone(phone);
            addres.setProvince(province);
            addres.setCity(city);
            addres.setArea(area);
            addres.setAddress(address);
            addres.setIsDefault(Integer.parseInt(isDefault));
            addressRep.save(addres);
            return r.s();
        }else{
            return r.t();
        }
    }

    /***
     * 修改地址信息
     * @param id
     * @param name
     * @param phone
     * @param province
     * @param city
     * @param area
     * @param address
     * @param isDefault
     * @return
     */
    @PostMapping("/editAddress")
    public ResponseInfo addAddress(String id,String name,String phone,String province,String city,String area,String address,String isDefault){
        if(!isOnle()){
            return r.t();
        }
        UserDto user= getUser();
        if(user!=null){
            AddressDto addressDto = addressRep.getOne(Integer.parseInt(id));
            if(addressDto!=null){
                if(isDefault.equals("1")){
                    AddressDto AddressDto = addressRep.findByUserIdDefault(user.getId());
                    if(AddressDto!=null){
                        AddressDto.setIsDefault(0);
                        addressRep.save(AddressDto);
                    }
                }
                addressDto.setUserId(user.getId());
                addressDto.setName(name);
                addressDto.setPhone(phone);
                addressDto.setProvince(province);
                addressDto.setCity(city);
                addressDto.setArea(area);
                addressDto.setAddress(address);
                addressDto.setIsDefault(Integer.parseInt(isDefault));
                addressRep.save(addressDto);
                return r.s();
            }else{
                return r.f("地址信息有误");
            }

        }else{
            return r.t();
        }
    }

    @PostMapping("/uploadCarImage")
    public ResponseInfo uploadCarImage(@RequestPart("img") MultipartFile img) throws IOException {
        if(!isOnle()){
            return r.t();
        }
        UserDto user= getUser();
        if(user!=null){
            String key = "UserHeard_"+user.getId()+"_"+new Date().getTime();
            QiniuUtils qiniuUtils = new QiniuUtils(baseConfig);
            DefaultPutRet resout = qiniuUtils.uploadFile(1,key,img.getInputStream());
            if(resout!=null){
                if(user.getHead()!=null&&!user.getHead().isEmpty()){
                    qiniuUtils.delFile(user.getHead().split(baseConfig.getUrl())[0]);
                }
                user.setHead(baseConfig.getUrl()+key);
                userRep.save(user);
                String imgs = "{\"imageUrl\":\""+baseConfig.getUrl()+key+"\"}";
                String res = HttpUtils.sendPostJSON("http://localhost:9090/OCR/licensePlate",imgs);
                System.out.println(res);
                return r.sd(res);
            }
        }
        return r.f();
    }

    /***
     * 手机登录获取验证码
     * @return
     */
    @PostMapping("/getLoginCode")
    public ResponseInfo getLoginCode(String phone){
        if(redisUtils.hasKey(phone+"&Tel")){
            return r.f("验证码发送频繁，请稍后再试！");
        }else{
            int time = 60;
            int code  = (int)((Math.random()*9+1)*1000);
            redisUtils.set(phone+"&Tel",code+"",time, TimeUnit.SECONDS);
            SmsUtils smsUtils = new SmsUtils();
            smsUtils.SendSms(900942,phone,code+"","1");
            return r.s();
        }
    }

    /***
     * 手机验证码登录
     * @param phone
     * @param code
     * @return
     */
    @PostMapping("/telLogin")
    public ResponseInfo telLogin(String phone,String code) {
        if(!redisUtils.hasKey(phone+"&Tel")){
            return r.f("登录失败，验证码失效");
        }else{
            String vCode = (String) redisUtils.get(phone+"&Tel");
            if(vCode!=null&&vCode!=""){
                if(vCode.equals(code)){
                    UserDto userDto = userRep.getUserByTel(phone);
                    TokenUtils tokenUtils = new TokenUtils(redisUtils);
                    if(userDto!=null){//更新
                        String token = tokenUtils.createToken(userDto);
                        if(token==null){
                            return r.f("登录失败，请稍后再试！");
                        }
                        userDto.setToken(token);
                        userRep.save(userDto);
                        return r.sd(userDto);
                    }else {//新注册
                        userDto = new UserDto();
                        String name = getName("微笑天使");
                        userDto.setName(name);
                        userDto.setHead("手机注册");
                        userDto.setCard("手机注册");
                        userDto.setPwd("手机注册");
                        userDto.setNick(name);
                        userDto.setSex(0);
                        userDto.setProvince("手机注册");
                        userDto.setCity("手机注册");
                        userDto.setOpenid("0");
                        userDto.setMoney(0D);
                        userDto.setState(0);
                        userDto.setIsPayPwd(0);
                        userDto.setIsPhone(1);
                        userDto.setIsUp(0);
                        userDto.setPhone(phone);
                        userDto.setIsDown(0);
                        userDto.setLevel(0);
                        userDto.setIsAdmin(0);
                        userDto.setCreat(new Date());
                        String token = tokenUtils.createToken(userDto);
                        userDto.setToken(token);
                        userRep.save(userDto);

                        RankDto levelLogDto = new RankDto();
                        levelLogDto.setUid(userDto.getId());
                        levelLogDto.setDl(0);
                        levelLogDto.setHhr(0);
                        levelLogDto.setJl(0);
                        levelLogDto.setZj(0);
                        rankRep.save(levelLogDto);

                        return r.sd(userDto);
                    }
                }else{
                    return r.f("登录失败，验证码失效");
                }
            }else{
                return r.f("登录失败，验证码失效");
            }
        }
    }

    /***
     * 绑定微信
     * @param code
     * @param encryptedData
     * @param iv
     * @return
     */
    @PostMapping("/bindWx")
    public ResponseInfo bindWx(String code, String encryptedData, String iv) {
        if(!isOnle()){
            return r.t();
        }
        UserDto tel= getUser();
        if(tel!=null){
            if (org.apache.commons.lang3.StringUtils.isBlank(code)) {
                return r.f("登录失败，请稍后再试！");
            }
            GetOpenIdUtil getOpenIdUtil = new GetOpenIdUtil();
            String newUser = getOpenIdUtil.getopenid(appId, code, secret);
            JSONObject jsonObject = JSONObject.fromObject(newUser);
            String openid = jsonObject.getString("openid");
            String session_key = jsonObject.getString("session_key");
            JSONObject user = getUserInfo(encryptedData, session_key, iv);
            WxMaUserInfo userInfo = (WxMaUserInfo) JSONObject.toBean(user, WxMaUserInfo.class);
            userInfo.setOpenId(openid);
            UserDto userDto = userRep.findUserByOpenid(openid);
            if (userDto != null) {//更新
                return r.f("绑定失败，该微信绑定了其他用户");
            } else {//新注册
                tel.setHead(userInfo.getAvatarUrl());
                tel.setCard(userInfo.getOpenId());
                tel.setPwd(userInfo.getOpenId());
                tel.setNick(userInfo.getNickName());
                tel.setSex(Integer.parseInt(userInfo.getGender()));
                tel.setProvince(userInfo.getProvince());
                tel.setCity(userInfo.getCity());
                tel.setOpenid(userInfo.getOpenId());
                userRep.save(tel);
                return r.sd(tel);
            }
        }else{
            return r.t();
        }
    }
    /***
     * 小程序登录
     * @param code
     * @param encryptedData
     * @param iv
     * @return
     */
    @PostMapping("/login")
    public ResponseInfo login(String code, String encryptedData, String iv) {
        if (org.apache.commons.lang3.StringUtils.isBlank(code)) {
            return r.f("登录失败，请稍后再试！");
        }
        GetOpenIdUtil getOpenIdUtil = new GetOpenIdUtil();
        String newUser = getOpenIdUtil.getopenid(appId,code,secret);
        JSONObject jsonObject = JSONObject.fromObject(newUser);
        String openid = jsonObject.getString("openid");
        String session_key = jsonObject.getString("session_key");
        System.out.println(iv);
        JSONObject user = getUserInfo(encryptedData,session_key,iv);
        WxMaUserInfo userInfo = (WxMaUserInfo) JSONObject.toBean(user,WxMaUserInfo.class);
        userInfo.setOpenId(openid);
        UserDto userDto = userRep.findUserByOpenid(openid);
        TokenUtils tokenUtils = new TokenUtils(redisUtils);
        if(userDto!=null){//更新
            String token = tokenUtils.createToken(userDto);
            if(token==null){
                return r.f("登录失败，请稍后再试！");
            }
            userDto.setHead(userInfo.getAvatarUrl());
            userDto.setCard(userInfo.getOpenId());
            userDto.setPwd(userInfo.getOpenId());
            userDto.setSex(Integer.parseInt(userInfo.getGender()));
            userDto.setProvince(userInfo.getProvince());
            userDto.setCity(userInfo.getCity());
            userDto.setOpenid(userInfo.getOpenId());
            userDto.setToken(token);
            userRep.save(userDto);
            return r.sd(userDto);
        }else {//新注册
            userDto = new UserDto();
            String name = getName("微笑天使");
            userDto.setName(name);
            userDto.setHead(userInfo.getAvatarUrl());
            userDto.setCard(userInfo.getOpenId());
            userDto.setPwd(userInfo.getOpenId());
            userDto.setNick(name);
            userDto.setSex(Integer.parseInt(userInfo.getGender()));
            userDto.setProvince(userInfo.getProvince());
            userDto.setCity(userInfo.getCity());
            userDto.setOpenid(userInfo.getOpenId());
            userDto.setMoney(0D);
            userDto.setState(0);
            userDto.setIsPayPwd(0);
            userDto.setIsPhone(0);
            userDto.setIsUp(0);
            userDto.setIsDown(0);
            userDto.setLevel(0);
            userDto.setIsAdmin(0);
            userDto.setCreat(new Date());
            String token = tokenUtils.createToken(userDto);
            userDto.setToken(token);
            userRep.save(userDto);

            RankDto levelLogDto = new RankDto();
            levelLogDto.setUid(userDto.getId());
            levelLogDto.setDl(0);
            levelLogDto.setHhr(0);
            levelLogDto.setJl(0);
            levelLogDto.setZj(0);
            rankRep.save(levelLogDto);

            return r.sd(userDto);
        }
    }
    /**
     * 获取信息
     */
    public JSONObject getUserInfo(String encryptedData,String sessionkey,String iv){
        // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decode(sessionkey);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);
        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                return JSONObject.fromObject(result);
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidParameterSpecException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        }
        return null;
    }
    /***
     * 随机生成一个新聊号
     * @param name
     * @return
     */
    public static String getName(String name){
        return name+ UUID.randomUUID().toString().replaceAll("-", "").substring(0,10).toUpperCase();
    }
    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
    @GetMapping("/info")
    public String info(String sessionKey,String signature, String rawData, String encryptedData, String iv) {
        final WxMaService wxService = WxMaConfiguration.getMaService(appId);

        // 用户信息校验
        if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            return "user check failed";
        }

        // 解密用户信息
        WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);

        return JsonUtils.toJson(userInfo);
    }

    /**
     * <pre>
     * 获取用户绑定手机号信息
     * </pre>
     */
    @GetMapping("/phone")
    public String phone(String sessionKey, String signature,String rawData, String encryptedData, String iv) {
        final WxMaService wxService = WxMaConfiguration.getMaService(appId);

        // 用户信息校验
        if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            return "user check failed";
        }

        // 解密
        WxMaPhoneNumberInfo phoneNoInfo = wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);

        return JsonUtils.toJson(phoneNoInfo);
    }

    /***
     * 是否在线
     * @return
     */
    public boolean isOnle() {
        TokenUtils tokenUtils = new TokenUtils(redisUtils);
        try {
            String token = req.getHeader("token");
            if(token==null||token.isEmpty()){
                return false;
            }
            return tokenUtils.TokenOnle(token);
        } catch (Exception e) {
            return false;
        }
    }

    /***
     * 获取当前用户对象
     * @return
     */
    public UserDto getUser() {
        UserDto user= userRep.getUserByToken(req.getHeader("token"));
        if(user!=null){
            return user;
        }else{
            return null;
        }
    }
/*
    @PostMapping("/orders")
    public ResponseInfo orders(String dateTime,String type,String page){
        if(!isOnle()){
            return r.t();
        }
        Integer lx = Integer.parseInt(type);
        UserDto user = getUser();
        if(user!=null){
            *//*currentPage;//当前页
            perPageRows;//每页的记录数
            totalRows;//总记录数：
            totalPages;//总页数：
            PageData;//分页内容*//*
            Page pages = new Page();
            pages.setCurrentPage(Integer.parseInt(page));
            pages.setPerPageRows(15);

            String sql = "";
            if(lx==0){
                sql = " SELECT * FROM publicorder  WHERE  DATE_FORMAT(pay_time,'%Y-%m') = '"+dateTime+"' AND userid = "+user.getId()+" AND state = 1  AND display = 0";
            }else{
                sql = " SELECT * FROM publicorder  WHERE  DATE_FORMAT(pay_time,'%Y-%m') = '"+dateTime+"' AND userid = "+user.getId()+" AND state = 1  AND type = "+type+" AND display = 0";
            }
            Query dataQuery = entityManager.createNativeQuery(sql,OrderDto.class);

            Integer currentPage = pages.getCurrentPage();//得到当前页
            Integer perPageRows = pages.getPerPageRows();//得到每页的记录数：

            dataQuery.setFirstResult((currentPage-1)*perPageRows);
            dataQuery.setMaxResults(perPageRows);
            Integer totalRows = dataQuery.getResultList().size();
            pages.setTotalRows(totalRows);//设置总数量
            int s = totalRows/15;
            int y = totalRows%15;
            pages.setTotalPages(s);
            if(y>0){
                pages.setTotalPages(s+1);
            }
            //1 红包支出  2红包收入  3第三方充值 4 提现支出
            Double income = 0d;
            Double expenditure = 0d;
            List<OrderDto> orderDtoList = dataQuery.getResultList();
            for(OrderDto orderDto :orderDtoList){
                if(orderDto.getState()==1){
                    if(orderDto.getType()==1||orderDto.getType()==4){
                        expenditure = expenditure+orderDto.getGoodPrice();
                    }else if(orderDto.getType()==2||orderDto.getType()==3){
                        income = income+ +orderDto.getGoodPrice();
                    }

                }
            }
            pages.setPageData(dataQuery.getResultList());
            pages.setIncome(income.toString());
            pages.setExpenditure(expenditure.toString());
            return r.sd(pages);
        }else{
            return r.f();
        }
    }*/




    /***
     * 退出登录
     * @return
     */
    @PostMapping("/out")
    public ResponseInfo out(){
        if(!isOnle()){
            return r.t();
        }
        UserDto user = getUser();
        if(user!=null){
            TokenUtils tokenUtils = new TokenUtils(redisUtils);
            tokenUtils.removeToken(req);
            user.setToken("");
            userRep.save(user);
            return r.sd("退出成功");
        }
        return r.f();
    }

    /***
     * 1.账号密码登录
     * @return
     */
/*    @PostMapping("/login")
    public ResponseInfo login(String phone, String pwd){
        UserDto s = userRep.Login(phone,pwd);
        if (s!=null) {
            TokenUtils tokenUtils = new TokenUtils(redisUtils);
            String token = tokenUtils.createToken(s);
            if(token==null){
                return r.f("登录失败，请稍后再试！");
            }
            s.setToken(token);
            s.setOnline(0);
            userRep.save(s);
            return r.sd(s);
        }else{
           return r.f("账号或密码错误！");
        }
    }*/

    /***
     * 绑定手机获取验证码
     * @param phone
     * @return
     */
    @PostMapping("/bindGetCode")
    public ResponseInfo bindGetCode(String phone){
        if(!isOnle()){
            return r.t();
        }
        UserDto user = getUser();
        if(user!=null){
            if(userRep.getIsPhone(phone)>0){
                return r.f("手机已被绑定，请更换其他手机号");
            }else{
                if(redisUtils.hasKey(phone+"&BIND")){
                    return r.f("验证码发送频繁，请稍后再试！");
                }else{
                    int time = 60;
                    int code  = (int)((Math.random()*9+1)*1000);
                    redisUtils.set(phone+"&BIND",code+"",time, TimeUnit.SECONDS);
                    SmsUtils smsUtils = new SmsUtils();
                    smsUtils.SendSms(900940,phone,code+"","1");
                    return r.s();
                }
            }
        }else{
            return r.t();
        }
    }

    /***
     * 校验绑定手机号验证码
     * @param code
     * @return
     */
    @PostMapping("/authBindCode")
    public ResponseInfo authBindCode(String code){
        if(!isOnle()){
            return r.t();
        }
        UserDto user = getUser();
        if(user!=null){
            if(redisUtils.hasKey(user.getPhone()+"&BIND")) {
                if(redisUtils.get(user.getPhone()+"&BIND").equals(code)){
                    return r.s();
                }
            }else{
                return r.f("验证码错误");
            }
        }else{
            return r.t();
        }
        return r.f("验证码错误，请稍后重试！");
    }

    /***
     * 绑定手机号
     * @param phone
     * @param code
     * @return
     */
    @PostMapping("/bindPhone")
    public ResponseInfo bindPhone(String phone,String code){
        if(!isOnle()){
            return r.t();
        }
        UserDto user = getUser();
        if(user!=null){
            if(redisUtils.hasKey(phone+"&BIND")) {
                if(redisUtils.get(phone+"&BIND").equals(code)){
                    user.setPhone(phone);
                    user.setIsPhone(1);
                    userRep.save(user);
                    return r.s();
                }
            }else{
                return r.f("验证码错误");
            }
        }else{
            return r.t();
        }
        return r.f("验证码错误，请稍后重试！");
    }


    /***
     * 校验支付密码
     * @param pwd
     * @return
     */
    @PostMapping("/authPayPwd")
    public ResponseInfo authPayPwd(String pwd){
        if(!isOnle()){
            return r.t();
        }
        UserDto user = getUser();
        if(user!=null){
            if(user.getIsPayPwd()==1){
                if(user.getPayPwd().equals(pwd)){
                    if(redisUtils.hasKey(user.getPhone()+"&PAYPWD")) {//错误记录存在
                        redisUtils.del(user.getPhone()+"&PAYPWD");
                    }
                    return r.s();
                }else{//如果错误，记录错误次数
                    if(redisUtils.hasKey(user.getPhone()+"&PAYPWD")) {//错误记录存在
                        int errorNum = (int) redisUtils.get(user.getPhone()+"&PAYPWD");
                        if(errorNum>3){
                            return r.f("失败次数超过3次，1小时后重试或修改支付密码");
                        }else{
                            redisUtils.set(user.getPhone()+"&PAYPWD",errorNum+1,1,TimeUnit.HOURS);
                        }
                    }else{//错误记录不存在
                        redisUtils.set(user.getPhone()+"&PAYPWD",1,1,TimeUnit.HOURS);
                    }
                }
            }else{
                return r.f("请先设置支付密码");
            }
        }else{
            return r.t();
        }
        return r.f("验证码错误，请稍后重试！");
    }
    /***
     * 校验支付密码验证码
     * @param code
     * @return
     */
    @PostMapping("/authPayPwdByCode")
    public ResponseInfo authPayPwdByCode(String code){
        if(!isOnle()){
            return r.t();
        }
        UserDto user = getUser();
        if(user!=null){
            if(redisUtils.hasKey(user.getPhone()+"&PAY")) {
                if(redisUtils.get(user.getPhone()+"&PAY").equals(code)){
                    return r.s();
                }
            }else{
                return r.f("验证码错误");
            }
        }else{
            return r.t();
        }
        return r.f("验证码错误，请稍后重试！");
    }
    /***
     * 验证码设置支付密码
     * @return
     */
    @PostMapping("/editPayPwdByCode")
    public ResponseInfo editPayPwdByCode(String code, String pwd){
        if(!isOnle()){
            return r.t();
        }
        UserDto user = getUser();
        if(user!=null){
            if(redisUtils.hasKey(user.getPhone()+"&PAY")) {
                if(redisUtils.get(user.getPhone()+"&PAY").equals(code)){
                    if(redisUtils.hasKey(user.getPhone()+"&PAYPWD")) {//错误记录存在
                        redisUtils.del(user.getPhone()+"&PAYPWD");
                    }
                    user.setPayPwd(pwd);
                    user.setIsPayPwd(1);
                    userRep.save(user);
                    return r.s();
                }
            }else{
                return r.f("验证码错误");
            }
        }else{
            return r.t();
        }
        return r.f("修改失败，请稍后重试！");
    }

    //getLoginCode
    /***
     * 设置支付密码获取验证码
     * @return
     */
    @PostMapping("/getPayCode")
    public ResponseInfo getPayCode(){
        if(!isOnle()){
            return r.t();
        }
        UserDto user = getUser();
        if(user!=null){
            if(redisUtils.hasKey(user.getPhone()+"&PAY")){
                return r.f("验证码发送频繁，请稍后再试！");
            }else{
                int time = 60;
                int code  = (int)((Math.random()*9+1)*1000);
                redisUtils.set(user.getPhone()+"&PAY",code+"",time, TimeUnit.SECONDS);
                SmsUtils smsUtils = new SmsUtils();
                smsUtils.SendSms(900942,user.getPhone(),code+"","1");
                return r.s();
            }
        }else{
            return r.t();
        }
    }



    /***
     * 6.获取个人信息
     * @return
     */
    @PostMapping("/getUserInfo")
    public ResponseInfo getUserInfo(){
        if(!isOnle()){
            return r.t();
        }
        UserDto user = getUser();
        if(user!=null){
            return r.sd(user);
        }else{
            return r.f("获取失败失败");
        }
    }

    /***
     * 7.上传头像
     * @param img
     * @return
     * @throws IOException
     */
    @PostMapping("/uploadHead")
    public ResponseInfo uploadHead(@RequestPart("img") MultipartFile img) throws IOException {
        if(!isOnle()){
            return r.t();
        }
        UserDto user= getUser();
        if(user!=null){
            String key = "UserHeard_"+user.getId()+"_"+new Date().getTime();
            QiniuUtils qiniuUtils = new QiniuUtils(baseConfig);
            DefaultPutRet resout = qiniuUtils.uploadFile(1,key,img.getInputStream());
            if(resout!=null){
                if(user.getHead()!=null&&!user.getHead().isEmpty()){
                    qiniuUtils.delFile(user.getHead().split(baseConfig.getUrl())[0]);
                }
                user.setHead(baseConfig.getUrl()+key);
                userRep.save(user);
                return r.sd(baseConfig.getUrl()+key);
            }
        }
        return r.f();
    }

    /***
     * 8.修改昵称
     * @return
     */
    @PostMapping("/editNick")
    public ResponseInfo editNick(String nick){
        if(!isOnle()){
            return r.t();
        }
        UserDto user= getUser();
        if(user!=null){
            if(user.getName().equals(nick)){
                return r.s();
            }
            int num = userRep.countNick(nick);
            if(num>0){
                return r.f("修改失败，名称已存在");
            }else{
                user.setName(nick);
                userRep.save(user);
                return r.s();
            }
        }
        return r.f();
    }

    /***
     * 11.修改性别
     * @param sex 1男 2女
     * @return
     */
    @PostMapping("/editSex")
    public ResponseInfo editSex(String sex){
        if(!isOnle()){
            return r.t();
        }
        if(!sex.equals("1")&&!sex.equals("2")){
            return r.f("请选择正确性别选项");
        }
        UserDto user = getUser();
        if(user!=null){
            user.setSex(Integer.parseInt(sex));
            userRep.save(user);
            return r.s();
        }
        return r.f();
    }
    /***
     * 12.修改地区
     * @param province 省份
     * @param city 城市
     * @return
     */
    @PostMapping("/editArea")
    public ResponseInfo editArea(String province, String city){
        if(!isOnle()){
            return r.t();
        }
        UserDto user= getUser();
        if(user!=null){
            user.setProvince(province);
            user.setCity(city);
            userRep.save(user);
            return r.s();
        }
        return r.f();
    }

    /***
     * 等级名称
     * @param level
     * @return
     */
    public String level(Integer level){
        if(level==0){
            return "会员";
        }else if(level==1){
            return "天使";
        }else if(level==2){
            return "市代";
        }else if(level==3){
            return "省代";
        }else if(level==4){
            return "分公司";
        }
        return "未知";
    }
}
